package com.alibaba.yygh.hosp.receiver;

import com.alibaba.yygh.hosp.service.ScheduleService;
import com.alibaba.yygh.model.hosp.Schedule;
import com.alibaba.yygh.rabbit.RabbitService;
import com.alibaba.yygh.rabbit.constant.MqConst;
import com.alibaba.yygh.vo.msm.MsmVo;
import com.alibaba.yygh.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * description: HospitalReceiver mq监听器
 * @author: gql
 * @date: 2021/11
 */
@Component
public class HospitalReceiver {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
            key = {MqConst.ROUTING_ORDER}
    ))
    public void receiver(OrderMqVo orderMqVo, Message message, Channel channel) throws IOException {
        // 1.如果包含剩余可以约数量,执行挂号流程
        if(null != orderMqVo.getAvailableNumber()) {
            // 根据排班id查询排班对象
            Schedule schedule = scheduleService.getByScheduleId(orderMqVo.getScheduleId());
            // 设置更新值
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            // 调用方法更新
            scheduleService.updateSchedule(schedule);
        } else {
            // 如果不包含剩余可以约数量,执行取消预约流程
            // 根据排班id查询排班对象
            Schedule schedule = scheduleService.getByScheduleId(orderMqVo.getScheduleId());
            // 设置更新值
            int availableNumber = schedule.getAvailableNumber().intValue() + 1;
            schedule.setAvailableNumber(availableNumber);
            // 调用方法更新
            scheduleService.updateSchedule(schedule);
        }


        // 2. 向短信模块发送消息,让其发送短信
        MsmVo msmVo = orderMqVo.getMsmVo();
        if(null != msmVo) {
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }
    }
}
